package it.unibo.deis.lia.servicemmhc.clock;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.dyno.visual.swing.layouts.Bilateral;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;

//VS4E -- DO NOT REMOVE THIS LINE!
public class ClientClock extends JFrame implements Runnable{

	private static final long serialVersionUID = 1L;
	private JButton jButton0;
	private JTextField jTextField0;
	private int port;
	private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";

	public ClientClock(int port) {
		this.port=port;
		initComponents();
	}

	private void initComponents() {
		setLayout(new GroupLayout());
		add(getJButton0(), new Constraints(new Bilateral(12, 12, 88),
				new Leading(67, 10, 10)));
		add(getJTextField0(), new Constraints(new Leading(10, 294, 10, 10),
				new Leading(19, 10, 10)));
		setSize(320, 106);
	}

	private JTextField getJTextField0() {
		if (jTextField0 == null) {
			jTextField0 = new JTextField();
			jTextField0.setEditable(false);
		}
		return jTextField0;
	}

	private JButton getJButton0() {
		if (jButton0 == null) {
			jButton0 = new JButton();
			jButton0.setText("Che ore sono?");
			jButton0.addMouseListener(new MouseAdapter() {

				public void mouseClicked(MouseEvent event) {
					jButton0MouseMouseClicked(event);
				}
			});
		}
		return jButton0;
	}

	private static void installLnF() {
		try {
			String lnfClassname = PREFERRED_LOOK_AND_FEEL;
			if (lnfClassname == null)
				lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
			UIManager.setLookAndFeel(lnfClassname);
		} catch (Exception e) {
			System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
					+ " on this platform:" + e.getMessage());
		}
	}
public void run(){
	installLnF();
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				ClientClock frame = new ClientClock(port);
				frame.setDefaultCloseOperation(ClientClock.EXIT_ON_CLOSE);
				frame.setTitle("ClientClock");
				frame.getContentPane().setPreferredSize(frame.getSize());
				frame.pack();
				frame.setLocation(400, 100);
				frame.setVisible(true);
			}
		});
}
	/**
	 * Main entry of the class. Note: This class is only created so that you can
	 * easily preview the result at runtime. It is not expected to be managed by
	 * the designer. You can modify it as you like.
	 */
	public static void main(String[] args) {
		installLnF();
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				ClientClock frame = new ClientClock(2900);
				frame.setDefaultCloseOperation(ClientClock.EXIT_ON_CLOSE);
				frame.setTitle("ClientClock");
				frame.getContentPane().setPreferredSize(frame.getSize());
				frame.pack();
				frame.setLocation(400, 100);
				frame.setVisible(true);
			}
		});
	}

	private void jButton0MouseMouseClicked(MouseEvent event) {
		
		try{
			int attempts = 5;
			
			Socket out = null;
			do {
				try {
					out = new Socket(InetAddress.getLocalHost(), port);
				} catch (BindException e) {
				} catch (Exception e) {
					Thread.sleep(1500);
					attempts--;
					if (attempts == 0)
						throw e;
					System.err
							.println("Impossibile aprire o trovare socket di risposta "
									+ e);
				}
			} while (attempts > 0 && out == null);
			ObjectOutputStream oos = new ObjectOutputStream(out
					.getOutputStream());
			oos.flush();
        Request richiesta = new Request("Che ore sono?");
        oos.writeObject(richiesta);
        oos.flush();
      // out.shutdownOutput();
        System.err.println("Richiesta inviata");
        ObjectInputStream ois = new ObjectInputStream(out.getInputStream());
       
        System.err.println("qui ci arrivo?");
        // legge la risposta
        Answer risposta = (Answer)ois.readObject();
        jTextField0.setText(""+risposta.getAnswer());
        //oos.flush();
        
  
		out.close();
        
		
		
		}catch (Exception e) {
			System.err.println("Errore nel client dell'orologio "+e);
			e.printStackTrace();
		} 
		
	}

}
